<template>
  <div>
    <transfer-change
      class="number-transfer"
      filter-placeholder="关键词搜索"
      v-model="target"
      :key="key"
      :data="objectList"
      :props="prop"
      :titles="['可选列表', '已选列表']"
      :left-default-checked="leftDefaultChecked"
      :format="{
        noChecked: '${total}',
        hasChecked: '${checked}/${total}'
      }"
      @left-check-change="leftCheckChange"
      @change="transferChange"
    >
      <template v-slot:header>
        <div>ljsdlfjlkj</div>
      </template>
      <el-pagination
        small
        slot="left-footer"
        align="right"
        @current-change="handleCurrentChange"
        :current-page="page.currentPage"
        :page-size="page.pageSize"
        :total="page.total"
        :pager-count="5"
        layout="prev, pager, next"
      ></el-pagination>
    </transfer-change>
  </div>
</template>

<script>
// import CommonService from "@/service/CommonService";
import TransferChange from "@/components/TransferChange";
import axios from "axios";
import debounce from "lodash/debounce";
export default {
  components: { TransferChange },
  props: {
    value: {
      type: Array,
      default: []
    },
    prop: {
      type: Object,
      default: () => {
        return {
          key: "value",
          label: "desc"
        };
      }
    }
  },
  computed: {
    target: {
      get() {
        return this.value;
      },
      set(v) {
        this.$emit("input", v);
      }
    }
  },
  data() {
    return {
      objectList: [],
      page: {
        currentPage: 1,
        pageSize: 20,
        total: 0,
        keword: ""
      },
      leftCheckKey: [], // 左侧选中的key
      leftCheckData: [], // 左侧保存的数据详情
      checkedData: [],
      key: Math.random(),
      leftDefaultChecked: [],
      targetData: []
    };
  },
  created() {
    this.getAccountList();
  },
  methods: {
    // 左侧按钮选中
    leftCheckChange(val, changeV) {
      // 改变的数据
      changeV.map(changeUser => {
        if (this.leftCheckKey.indexOf(changeUser) > -1) {
          // 取消
          this.leftCheckKey = this.leftCheckKey.filter(x => x != changeUser);
          this.leftCheckData = this.leftCheckData.filter(
            x => x[this.prop.key] != changeUser
          );
        } else {
          // 添加
          this.leftCheckKey.push(changeUser);
          let data = this.objectList.find(
            item => item[this.prop.key] === changeUser
          );
          this.leftCheckData.push(data);
        }
      });
    },
    //穿梭change
    transferChange(current, direction, move) {
      // 保存已经选中的数据
      if (direction === "right") {
        // 向右添加
        // 需要将向右添加的数据保存下来，在切换数据的时候，添加到当前列表中，方便回显
        this.objectList = this.removeArr([
          ...this.leftCheckData,
          ...this.objectList
        ]);
        this.target = [
          ...new Set([...current, ...this.leftCheckKey, ...this.target])
        ];
        this.targetData = this.removeArr([
          ...this.leftCheckData,
          ...this.targetData
        ]);
        // 提交到右边后，清空选中的数据
        this.leftCheckKey = [];
        this.leftCheckData = [];
      } else {
        // 向右的时候要同步减少leftCheckData,和leftCheckKey的值
        move.map(item => {
          let keyIndex = this.leftCheckKey.findIndex(
            subItem => subItem === item
          );
          this.leftCheckKey.splice(keyIndex, 1);
          let dataIndex = this.leftCheckData.findIndex(
            third => third[this.prop.key] === item
          );
          this.leftCheckData.splice(dataIndex, 1);
          let tagetIndex = this.targetData.findIndex(
            a => a[this.prop.key] === item
          );
          this.targetData.splice(tagetIndex, 1);
        });
      }
    },
    handleCurrentChange(val) {
      // 保留选中的数据，添加当前数据中
      this.page.currentPage = val;
      this.getAccountList();
    },
    getAccountList: debounce(function() {
      const { currentPage, pageSize, keword } = this.page;
      axios({
        method: "get",
        url: "http://10.202.43.166:8080/dev/securecenter/api/v1/account/list",
        headers: {
          UserInfo: "admin",
          tenantId: "3523112ebac379703ed302592d9160ba"
        },
        params: {
          currentPage,
          pageSize,
          keword
        }
      })
        .then(res => {
          const { data } = res.data;
          this.page.total = data.total;
          let arr = [...data.rows, ...this.targetData];
          this.objectList = this.removeArr(arr);
        })
        .then(() => {
          // 回显左侧选中的数据
          this.leftDefaultChecked = [];
          this.leftCheckKey.map(item => {
            let data = this.objectList.find(
              subItem => subItem[this.prop.key] === item
            );
            if (data) {
              this.leftDefaultChecked.push(data[this.prop.key]);
            }
          });
          // 强制初始化，确保左侧数据能够回显
          this.key = Math.random();
        });
    }),
    // 数组对象去重
    removeArr(arr) {
      const res = new Map();
      return arr.filter(
        arr => !res.has(arr[this.prop.key]) && res.set(arr[this.prop.key], 1)
      );
    },
    // 重置
    resetData() {
      this.leftDefaultChecked = [];
      this.leftCheckKey = [];
      this.leftCheckData = [];
      this.target = [];
      this.targetData = [];
      this.key = Math.random();
    }
  }
};
</script>


<style scoped lang="scss">
.number-transfer {
  margin: 200px;
  /deep/.el-transfer-panel {
    width: 250px;
  }
  /deep/.el-transfer-panel__body {
    margin-bottom: 40px;
  }
}
</style>
